package com.opdar.platform.gateway.base;

import com.opdar.platform.core.base.Context;
import com.opdar.platform.core.base.Router;
import com.opdar.platform.core.base.RouterManager;
import com.opdar.platform.gateway.point.PointManager;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.UUID;

/**
 * Created by shiju on 2017/12/11.
 */
public class ApiService {

    private String url;

    private Logger logger = LoggerFactory.getLogger("PointInfo");

    private ApiService(String url) {
        this.url = url;
    }

    public static ApiService create(String host, Integer port , String module){
        String url = "http://"+host+":"+port+"/api/"+module+"/";
        return new ApiService(url);
    }

    public byte[] invoke(String router,NameValuePair...params) {
        OkHttpClient client = new OkHttpClient();
        StringBuilder logBuilder = new StringBuilder();
        Request.Builder build = new Request.Builder().url(url+router);
        {
            Router router1 = RouterManager.getCurrentRouter();
            if(router1!= null){
                String routerName = router1.getName();
                build.addHeader("X-Router",routerName);
                logBuilder.append("router=").append(routerName).append("|");
            }
            try{
                String uniqueId = Context.getRequest().getHeader("X-Api-UniqueID");
                if(!StringUtils.isEmpty(uniqueId)){
                    logBuilder.append("uniqueId=").append(uniqueId).append("|");
                }else{
                    uniqueId = UUID.randomUUID().toString();
                }
                build.addHeader("uniqueId",uniqueId);

                String deep = Context.getRequest().getHeader("X-Api-Deep");
                int _deep = 0;
                logBuilder.append("deep=").append(deep).append("|");
                if(!StringUtils.isEmpty(deep)){
                    _deep = Integer.valueOf(deep)+1;
                }
                build.addHeader("deep",String.valueOf(_deep));
            }catch (Exception ignored){}
            String code = PointManager.getCurrentCode();
            if(!StringUtils.isEmpty(code)){
                build.addHeader("X-Gateway-Code", code);
                logBuilder.append("code=").append(code).append("|");
            }
            if(logBuilder.length() > 0){
                logBuilder.deleteCharAt(logBuilder.length()-1);
                logger.info(logBuilder.toString());
            }
        }
        FormBody.Builder formBuilder = new FormBody.Builder();
        for(NameValuePair pair:params){
            try{
                formBuilder.add(pair.getKey(),String.valueOf(pair.getValue()));
            }catch (Exception ignored){}
        }
        build.method("POST",formBuilder.build());
        try {
            Response response = client.newCall(build.build()).execute();
            return response.body().bytes();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
